var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var _height = $(parent).height()-220,_width = $(parent).width()-36;

var Utils = {
	doQueryReward : function(){
		commonDia = $.dialog({
			title : '选择奖励',
			content : 'url:'+config.BASEPATH+'sys/reward/to_list_dialog',
			data : {multiselect:true},
			width : 480,
			height : 420,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].rw_code);
					names.push(selected[i].rw_name);
				}
				$("#reward_codes").val(codes.join(","));
				$("#reward_names").val(names.join(","));
			},
			cancel:true
		});
	},
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:true,module:'kpi'},
			width : 480,
			height : 420,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var datas = [];
				for(var i=0;i<selected.length;i++){
					var data = {};
					data.id = selected[i].sp_code;
					data.kpl_code = selected[i].sp_code;
					data.kpl_name = selected[i].sp_name;
					datas.push(data);
				}
				Utils.addDatas(datas);
			},
			cancel:true
		});
	},
	doQueryEmpGroup : function(){
		commonDia = $.dialog({
			title : '选择员工组',
			content : 'url:'+config.BASEPATH+'base/empgroup/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var datas = [];
				for(var i=0;i<selected.length;i++){
					var data = {};
					data.id = selected[i].eg_code;
					data.kpl_code = selected[i].eg_code;
					data.kpl_name = selected[i].eg_name;
					datas.push(data);
				}
				Utils.addDatas(datas);
			},
			cancel:true
		});
	},
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择员工',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var datas = [];
				for(var i=0;i<selected.length;i++){
					var data = {};
					data.id = selected[i].em_code;
					data.kpl_code = selected[i].em_code;
					data.kpl_name = selected[i].em_name;
					datas.push(data);
				}
				Utils.addDatas(datas);
			},
			cancel:true
		});
	},
	addDatas:function(datas){
		var ids = $("#grid").jqGrid('getDataIDs');
		var exist = false;
		for(var i=0;i<datas.length;i++){
			var data = datas[i];
			exist = false;
			for(var j=0;j < ids.length;j++){
				var rowData = $('#grid').jqGrid('getRowData',ids[j]);
				if(rowData.kpl_code == data.kpl_code){
					exist = true;
				}
			}
			if(!exist){
				$("#grid").addRowData(data.id, data,'first');
			}
		}
		$('#grid').jqGrid('delRowData', 0);
	},
	doQueryKpi : function(){
		commonDia = $.dialog({
			title : '选择KPI指标',
			content : 'url:'+config.BASEPATH+'sys/kpi/to_list_dialog',
			data : {multiselect:true},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var datas = [];
				for(var i=0;i<selected.length;i++){
					var data = {};
					data.id = selected[i].ki_code;
					data.ki_code = selected[i].ki_code;
					data.ki_name = selected[i].ki_name;
					datas.push(data);
				}
				Utils.addDatas_Detail(datas);
			},
			cancel:true
		});
	},
	addDatas_Detail:function(datas){
		var ids = $("#detailGrid").jqGrid('getDataIDs');
		var exist = false;
		for(var i=0;i<datas.length;i++){
			var data = datas[i];
			exist = false;
			for(var j=0;j < ids.length;j++){
				var rowData = $('#detailGrid').jqGrid('getRowData',ids[j]);
				if(rowData.ki_code == data.ki_code){
					exist = true;
				}
			}
			if(!exist){
				$("#detailGrid").addRowData(data.id, data,'first');
			}
		}
		$('#detailGrid').jqGrid('delRowData', 0);
	}
};

var handle = {
	save:function(){
		var params = {};
		var kpipk = {};
		kpipk.kp_type = $("#kp_type").val();
		kpipk.kp_begin = $("#begindate").val();
		kpipk.kp_end = $("#enddate").val();
		kpipk.kp_remark = $("#kp_remark").val();
		kpipk.kp_score = parseInt($("#kp_score").val());
		kpipk.reward_codes = $("#reward_codes").val();
		var details = [];
		var kpis = [];
		var ids = $("#grid").jqGrid('getDataIDs');
		var ids_2 = $("#detailGrid").jqGrid('getDataIDs');
		for(var i=0;i < ids.length;i++){
			var rowData = $("#grid").jqGrid("getRowData", ids[i]);
			if(rowData.kpl_code == ""){
				continue;
			}
			var detail = {};
			detail.kpl_code = rowData.kpl_code;
			detail.kpl_name = rowData.kpl_name;
			details.push(detail);
		}
		for(var i=0;i < ids_2.length;i++){
			var rowData = $("#detailGrid").jqGrid("getRowData", ids_2[i]);
			if(rowData.ki_code == ""){
				continue;
			}
			kpis.push(rowData.ki_code);
		}
		if(details.length == 0){
			Public.tips({type: 2, content : '请选择店铺、员工组或员工！'});
			return;
		}
		if(kpis.length == 0){
			Public.tips({type: 2, content : '请选择KPI指标！'});
			return;
		}
		if(isNaN(kpipk.kp_score)){
			Public.tips({type: 2, content : '请输入标准分数！'});
			return;
		}
		params.kpipk = Public.encodeURI(JSON.stringify(kpipk));
		params.details = Public.encodeURI(JSON.stringify(details));
		params.kpis = kpis.join(",");
		$("#btn-save").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"shop/kpipk/save",
			data:params,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功'});
					handle.loadData(data.data);
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-save").attr("disabled",false);
			}
		});
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.kp_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-plus" title="新增">&#xe639;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initDetailGrid();
		this.initEvent();
	},
	initDom:function(){
		$("#begindate").val(config.TODAY);
		$("#enddate").val(config.TODAY);
		this.initKpType();
	},
	initKpType:function(){//类型：0-店铺，1-员工组，2-员工
		var data = [
		    {Code:"0",Name:"店铺"},
		    {Code:"1",Name:"员工组"},
		    {Code:"2",Name:"员工"}
		];
		$('#span_kp_type').combo({
			data:data,
			value: 'Code',
			text: 'Name',
			width :158,
			height:80,
			listId:'',
			defaultSelected: 0,
			editable: false,
			callback:{
				onChange: function(data){
					$("#kp_type").val(data.Code);
					$("#grid").jqGrid("clearGridData").trigger("reloadGrid");
					switch(data.Code){
						case '0' : 
							$('#grid').setLabel("kpl_code","店铺编号");
							$('#grid').setLabel("kpl_name","店铺名称");
							break ;
						case '1' : 
							$('#grid').setLabel("kpl_code","员工组编号");
							$('#grid').setLabel("kpl_name","员工组名称");
							break ;
						case '2' : 
							$('#grid').setLabel("kpl_code","员工编号");
							$('#grid').setLabel("kpl_name","员工名称");
							break ;
						default :
							break ;
					}
				}
			}
		}).getCombo();
	},
	addEmptyGridData:function(){
    	var gridData = {kpl_code:'',kpl_name:''};
    	$("#grid").addRowData(0, gridData,'first');
    },
	initGrid:function(){
		var colModel = [
	    	{label:'操作',name: 'operate', width: 60, fixed:true, formatter: handle.operFmatter,sortable:false},
	    	{label:'店铺编号',name: 'kpl_code', index: 'kpl_code', width: 140, title: false},
	    	{label:'店铺名称',name: 'kpl_name', index: 'kpl_name', width: 200, title: false}
	    ];
		$('#grid').jqGrid({
			loadonce:true, //只从后台加载一次数据，datatype被修改为local,如果弹出框想要查询则再开启为json
			datatype: 'local',
			width:_width/2,
			height: _height,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			multiselect:false,//多选
			viewrecords: true,
			cmTemplate: {sortable:false,title:false},
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			rowNum:999,//每页条数
			shrinkToFit:false,//表格是否自动填充
			jsonReader: {
				root: "data",
				repeatitems : false	,
				id: 'id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.addEmptyGridData();
			},
			loadError: function(xhr, status, error){		
				
			}
	    });
	},
	addEmptyDetailGridData:function(){
    	var gridData = {ki_code:'',ki_name:''};
    	$("#detailGrid").addRowData(0, gridData,'first');
    },
	initDetailGrid:function(){
		var self=this;
		var colModel = [
		    {label:'操作',name: 'operate', width: 60, fixed:true, formatter: handle.operFmatter},
	    	{label:'KPI编号',name: 'ki_code', index: 'ki_code', width: 140},
	    	{label:'KPI名称',name: 'ki_name', index: 'ki_name', width: 200}
	    ];
		$('#detailGrid').jqGrid({
			loadonce:true, //只从后台加载一次数据，datatype被修改为local,如果弹出框想要查询则再开启为json
			datatype: 'local',
			width:_width/2,
			height: _height,
			altRows:true,
			gridview: true,				
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			multiselect:false,//多选
			viewrecords: true,
			pager: '#pageDetail',//分页
			cmTemplate: {sortable:false,title:false},
			page: 1, //只有一页
			pgbuttons:false,
			recordtext:'共 {2} 条',
			pgtext:false,
			rowNum:99999,//每页条数
			shrinkToFit:false,//表格是否自动填充
			jsonReader: {
				root: "data",
				repeatitems : false	,
				id: 'id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.addEmptyDetailGridData();
			},
			loadError: function(xhr, status, error){
			}
	    });
	},
	initEvent:function(){
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		$('#grid').on('click', '.operating .ui-icon-plus', function (e) {
            e.preventDefault();
            var id = $(this).parent().data('id');
            var kp_type = $("#kp_type").val();
			if(kp_type == '0'){
				Utils.doQueryShop();
			}else if(kp_type == '1'){
				Utils.doQueryEmpGroup();
			}else if(kp_type == '2'){
				Utils.doQueryEmp();
			}
        });
		$('#grid').on('click', '.operating .ui-icon-trash', function (e) {
            e.preventDefault();
            var id = $(this).parent().data('id');
            if(id != 0){
            	var ids = $("#grid").jqGrid('getDataIDs');
            	$.dialog.confirm('数据删除后将不能恢复，请确认是否删除？',function(){
            		$('#grid').jqGrid('delRowData', id);
            		if(ids.length == 1){
            			THISPAGE.addEmptyGridData();
            		}
            	});
            }
        });
		$('#detailGrid').on('click', '.operating .ui-icon-plus', function (e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			Utils.doQueryKpi();
		});
		$('#detailGrid').on('click', '.operating .ui-icon-trash', function (e) {
            e.preventDefault();
            var id = $(this).parent().data('id');
            if(id != 0){
            	var ids = $("#detailGrid").jqGrid('getDataIDs');
            	$.dialog.confirm('数据删除后将不能恢复，请确认是否删除？',function(){
            		$('#detailGrid').jqGrid('delRowData', id);
            		if(ids.length == 1){
            			THISPAGE.addEmptyDetailGridData();
            		}
            	});
            }
        });
	}
};

THISPAGE.init();